package com.hiyee.platform.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hiyee.platform.config.Constant;
import com.hiyee.platform.config.FileProperties;
import com.hiyee.platform.response.ResponseJsonResult;
import com.hiyee.platform.response.ResponseStatusEnum;
import com.hiyee.platform.service.RabbitMqService;
import com.hiyee.platform.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    RabbitMqService rabbitMqService;
    @Autowired
    FileProperties fileProperties;

    @PostMapping("/upload")
    public ResponseJsonResult upload(@RequestBody MultipartFile file, @RequestParam String scene) throws IOException {
        // 场景是否支持
        if(!Constant.UPLOAD_SCENE_LIST.contains(scene)) {
            return ResponseJsonResult.error(ResponseStatusEnum.UPLOAD_SCENE_NOT_FOUND);
        }
        // 判断文件类型
        List<String> fileExtensionList = StrUtil.split(file.getOriginalFilename(), ".");
        String extension = fileExtensionList.get(1);
        System.out.println(extension);
        if(StrUtil.isBlank(extension) || !(StrUtil.equals(extension, "xlsx") || StrUtil.equals(extension, "xls"))) {
            return ResponseJsonResult.error(ResponseStatusEnum.UPLOAD_FILE_EXT_ERROR);
        }

        // 上传文件
        String savePath = fileProperties.getServerPath() + IdUtil.simpleUUID() + "." + extension;
        file.transferTo(new File(savePath));

        // 发布到 rabbitmq
        rabbitMqService.publish(FileUtil.getFileMap("CITY_CODE", "UPLOAD", savePath));

        return ResponseJsonResult.success();
    }
}
